﻿namespace VS.Web.Services
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Linq;
    using System.ServiceModel.DomainServices.EntityFramework;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;
    using VS.Web.Model;
    using System.ServiceModel.DomainServices.Server.ApplicationServices;
    using System.Web.Security;
    using System.Runtime.Serialization;
    using System.ServiceModel.Activation;


    // Implements application logic using the ModelContainer context.
    // TODO: Add your application logic to these methods or in additional methods.
    // TODO: Wire up authentication (Windows/ASP.NET Forms) and uncomment the following to disable anonymous access
    // Also consider adding roles to restrict access as appropriate.
    // [RequiresAuthentication]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    
    [EnableClientAccess()]
    public class AuthenticationService : LinqToEntitiesDomainService<WebContext>, IAuthentication<User>
    {

        // TODO:
        // Consider constraining the results of your query method.  If you need additional input you can
        // add parameters to this method or create additional query methods with different names.
        // To support paging you will need to add ordering to the 'Users' query.
        //public IQueryable<User> GetUsers()
        //{
        //    return this.ObjectContext.Users;
        //}

        public void InsertUser(User user)
        {
            if ((user.EntityState != EntityState.Detached))
            {
                this.ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Added);
            }
            else
            {
                this.ObjectContext.Users.AddObject(user);
            }
        }

        public void UpdateUser(User currentUser)
        {
            if ((this.ServiceContext.User == null) ||
                (this.ServiceContext.User.Identity == null) ||
                !string.Equals(this.ServiceContext.User.Identity.Name, currentUser.Name, System.StringComparison.Ordinal))
            {
                throw new UnauthorizedAccessException("You are only authorized to modify your own profile.");
            }

            this.ObjectContext.Users.AttachAsModified(currentUser, this.ChangeSet.GetOriginal(currentUser));
        }

        //public void DeleteUser(User user)
        //{
        //    if ((user.EntityState != EntityState.Detached))
        //    {
        //        this.ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Deleted);
        //    }
        //    else
        //    {
        //        this.ObjectContext.Users.Attach(user);
        //        this.ObjectContext.Users.DeleteObject(user);
        //    }
        //}

        public User GetUser()
        {
            if ((this.ServiceContext != null) &&
                (this.ServiceContext.User != null) &&
                this.ServiceContext.User.Identity.IsAuthenticated)
            {
                return this.GetUser(this.ServiceContext.User.Identity.Name);
            }
            return AuthenticationService.DefaultUser;
        }

        public User Login(string userName, string password, bool isPersistent, string customData)
        {
            if (this.ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, isPersistent);
                return this.GetUser(userName);
            }
            return null;
        }
       
        public User Logout()
        {
            FormsAuthentication.SignOut();
            return AuthenticationService.DefaultUser;
        }

        private User GetUser(string userName)
        {
            return this.ObjectContext.Users.First(u => u.Name == userName);
        }

        private bool ValidateUser(string username, string password)
        {
            User user = this.ObjectContext.Users.FirstOrDefault(u => u.Name == username);
            return (user != null && user.Password == password);
        }

        private static User DefaultUser = new User()
        {
            Name = string.Empty,
            Password = string.Empty,
            FullName = string.Empty,
            Email = string.Empty,
        };

    }

    
}


